package com.源码分析;

import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.context.Context;

public class ContextDemo {

	private Logger log = LoggerFactory.getLogger(ContextDemo.class);

	@Test
	@Ignore
	public void test() {
		Flux.just("foo")
	    .flatMap(v -> Mono.subscriberContext().map(ctx -> v + ctx.get("initial")))
		.subscriberContext(Context.of("initial", "value"))
		.subscribe(x -> {
			System.out.println(x);
		});
	}

	@Test
	@Ignore
	public void test2() {
		Flux.just("foo")
		.handle((d, c) -> c.next(d + c.currentContext().get("initial")))
		.subscriberContext(Context.of("initial", "value"))
		.subscribe(x -> {
			System.out.println(x);
		});
	}

	// 流顶部的可用Context包含此流中可用的整个Context，其中流的中间部分只能访问在下游中定义的Context，而位于非常底部(具有id初始值)的上下文消费者上下文为空
	@Test
	public void test3() {
		printCurrentContext("top")
		.subscriberContext(Context.of("top", "context"))
		.flatMap(__ -> printCurrentContext("middle"))
		.subscriberContext(Context.of("middle", "context"))
		.flatMap(__ -> printCurrentContext("bottom"))
		.subscriberContext(Context.of("bottom", "context"))
		.flatMap(__ -> printCurrentContext("initial"))
		.block();
	}

	Mono<Context> printCurrentContext(String id) {
		return Mono.subscriberContext().doOnNext(context -> print(id, context));
	}

	private void print(String id, Context context) {
		log.info("id: {}, context: {}", id, context);
	}

}
